<?php
/**
 * OrganizationController class file.
 *
 * @package   controllers
 * @since     1.0
 * @filesource
 */

/**
 * Controller for Organizations. Contains actions to manage the organizations.
 * Controller class is also responsible for rendering page.
 */
class OrganizationController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @var string the name of the default action. In this case, admin is the default action, meaning
	 * when request the controller not specifying the action, the action that will be called.
	 */
	public $defaultAction='admin';

	/**
	 * Return a list of filters that will be used to control access.
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter which is declared in $this->filters().
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // only allow admin to perform all actions
				'actions'=>array('create','update','admin','delete'),
				'roles'=>array('admin'),
		),
		array('deny',  // deny all other users
				'users'=>array('*'),
		),
		);
	}


	/**
	 * Creates a new organization.
	 * This action will display a form for creating a organization if no data posted back.
	 * If data posted back, it will validate the data and try to save it to database.
	 * If creation is successful, the browser will be redirected to the 'admin' page.
	 */
	public function actionCreate()
	{
		$model=new Organization;
		
		// AjaxValidation is used on the Creation page.
		$this->performAjaxValidation($model);

		if(isset($_POST['Organization']))
		{
			$model->attributes=$_POST['Organization'];
			$model->active=1; //default value when creating is 1(active).
			if($model->save()){
				//if saving successfully, then create the organization's folder for saving signal files.
				$orgFolder=$model->getFullUploadFolder();
				if(!file_exists($orgFolder)){
					@mkdir($orgFolder);
				}
				$this->redirect(array('admin'));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular organization.
	 * This action will display a form for updating a organization if no data posted back.
	 * If data posted back, it will validate the data and try to save it to database.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the organization to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		
		$this->performAjaxValidation($model);

		if(isset($_POST['Organization']))
		{
			$model->attributes=$_POST['Organization'];
			if($model->save()){
				//if saving successfully, then check if upload folder is updated, then make a new folder.
				$path=$model->getFullUploadFolder();
				if (!is_dir($path)) {
					mkdir($path);
				}
				$this->redirect(array('admin'));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular organization.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the organization to be deleted
	 * @throws CHttpException If the request is not POST request
	 * @throws CHttpException If deletion of organization folder is not successful
	 */
	public function actionDelete($id)
	{
		// we only allow deletion via POST request
		if(Yii::app()->request->isPostRequest)
		{
			$model = $this->loadModel($id);
			if (DataUtil::rrmdir($model->getFullUploadFolder())) {
				//if all files and directory under organization folder and organization folder are deleted successfully, the record will be removed from database.
				$model->delete();
			}
			else
				throw new CHttpException(404,'Deleting organization\'s folder is not successful. Please contact administrator to solve this issue.');
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all organizations.
	 * This action will render an admin page using Organization's method search() to produce a list of organizations.
	 * This method will produce a list of organizations by search conditions.
	 */
	public function actionAdmin()
	{
		$model=new Organization('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Organization']))
		$model->attributes=$_GET['Organization'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns Organization object based on the primary key given in the GET variable.
	 * @param integer the ID of the model to be loaded
	 * @return Organization the Organization for the given ID.
	 * @throws CHttpException If the Organization object is not found
	 */
	public function loadModel($id)
	{
		$model=Organization::model()->findByPk((int)$id);
		if($model===null)
		throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation. The result will appear on the page.
	 * @param Organization the object to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='organization-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
